import { pull, push } from '@/utils/fp';
import { useEffect } from 'react';
import { useCall } from '.';

let seq = [];
const raf = () => {
  for (const fn of seq) {
    fn?.();
  }
};

if (typeof window === 'undefined') {
  // SSR
} else if ('requestAnimationFrame' in window) {
  const doRaf = () => {
    raf();
    requestAnimationFrame(doRaf);
  };
  requestAnimationFrame(doRaf);
} else {
  window.setInterval(raf, 100);
}

const enq = (fn) => {
  seq = push(fn)(seq);
};

const deq = (fn) => {
  seq = pull(fn)(seq);
};

/**
 * 使用`requestAnimationFrame`执行函数
 * @param {Function} fn
 * @param {any[]} args
 */
function useRaf(fn, ...args) {
  const cb = useCall(fn, ...args);

  useEffect(() => {
    enq(cb);
    return () => {
      deq(cb);
    };
  }, []);
}

export default useRaf;
